package com.ftp.longdistance.thread;

import cn.hutool.core.thread.ThreadFactoryBuilder;
import com.ftp.longdistance.LongDistanceApplication;
import com.ftp.longdistance.system.SystemSettings;
import org.apache.tomcat.util.threads.ThreadPoolExecutor;

import java.text.NumberFormat;
import java.util.concurrent.*;

/**
 * @author TanYongPeng
 * <p>
 *     当前类是为了关闭输出日志的时候加载控制台的百分比，仅此而已
 *     为了springboot和百分比动画能同时进行，
 *     采用了线程池的方式，保证两个线程能各尽其职
 *     也可以直接在启动类调用 SystemSettings.getInstance().comm(....).run()
 * </p>
 */
public enum  ExeThread {
    /**
     * this
     */
    INSTANCE ;

    /**
     * 线程池的基本大小
     */
    private int corePoolSize = 10;
    /**
     * 线程池最大数量
     */
    private int maximumPoolSizeSize = 100;
    /**
     * 线程活动保持时间
     */
    private long keepAliveTime = 1;

    /**
     * 任务队列
     */
    ArrayBlockingQueue workQueue = new ArrayBlockingQueue(10);

    public void run(boolean log,Class<?> primarySource,String... args){
        thread(log,primarySource,args);
    }

    public void run(Class<?> primarySource,String... args){
        thread(true,primarySource,args);
    }

    private void thread(boolean log,Class<?> primarySource,String... args){
        ThreadPoolExecutor executor = new ThreadPoolExecutor(
                corePoolSize,
                maximumPoolSizeSize,
                keepAliveTime,
                TimeUnit.SECONDS,
                workQueue,
                new ThreadFactoryBuilder().setNamePrefix("XX-task-%d").build());
        executor.execute(() -> SystemSettings.getInstance().comm(log,primarySource,args).run());
        if (!log){executor.execute(this::log);}
    }


    private void log() {
            System.err.print("Remote Connection UI 启动中 ... ");
            NumberFormat num = NumberFormat.getPercentInstance();
            num.setMaximumIntegerDigits(4);
            num.setMaximumFractionDigits(3);
            for (int i = 1; i <= 5; i++) {
                double percent = i/5.0;
                String temp = num.format(percent);
                System.err.print(temp);
                try {
                    Thread.sleep(597);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                // 退格
                if (i!=5) {
                    for (int j = 0; j < temp.length(); j++) {
                        System.err.print("\b");
                    }
                }
            }
            System.err.println();

    }

}
